﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using BlogDemo.Infrastructure.Database;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;

namespace BlogDemo.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
          
            var host = CreateWebHostBuilder(args).Build();

            Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Debug()
               .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
               .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.File(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt"), rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true)
               .CreateLogger();
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var ctx = services.GetRequiredService<BlogContext>();
                var logger = services.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(Program));
                try
                {
                    BlogContextSeed.SeedAsync(ctx, 5).Wait();
                }
                catch (Exception ex)
                {
                    logger.LogError(ex.Message);
                }
            }
            host.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseSerilog()
            .UseUrls("http://localhost:5001")
            .UseStartup(typeof(Startup).GetTypeInfo().Assembly.FullName);
        //.UseStartup<Startup>();
    }
}
